package com.platform.common.util.file;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Decoder;
import com.platform.common.util.DateUtils;

public class FileUtil {

	public static void main(String[] args) {
		String filePath = "E:\\sqlserver内存优化.docx";
		String outFilePath = "E:\\";
		String outFileName = "2.docx";

		byte[] bytes = FileUtil.getBytes(filePath);
		FileUtil.getFile(bytes, outFilePath, outFileName);

		// System.out.println(fileToString("src/main/java/com/thinkgem/jeesite/modules/gsb/entity/fileopen.json"));
	}

	/**
	 * 将文件转为二进制数据
	 * 
	 * @Desc:
	 * @date:Nov 30, 2017 2:31:12 PM
	 * @param filePath
	 *            ：文件路径名
	 * @return
	 */
	public static byte[] getBytes(String filePath) {
		byte[] buffer = null;
		try {
			buffer = IOUtils.toByteArray(new FileInputStream(new File(filePath)));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	/**
	 * 将二进制数据生成文件
	 * 
	 * @Desc:
	 * @date:Nov 30, 2017 2:31:35 PM
	 * @param buffer
	 *            ：二进制数据文件
	 * @param filePath
	 *            :文件存放路径
	 * @param fileName
	 *            ：文件名称
	 */
	public static void getFile(byte[] buffer, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
				dir.mkdirs();
			}
			File file = new File(filePath + "\\" + fileName);
			bos = new BufferedOutputStream(new FileOutputStream(file));
			IOUtils.write(buffer, bos);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(bos);
		}
	}

	/**
	 * Jason ZHAO 读取txt文件的内容
	 * 
	 * @param filePath
	 *            想要读取的文件对象的路径
	 * @return 返回文件内容
	 */
	public static String fileToString(String filePath) {
		File file = new File(filePath);
		StringBuilder result = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
				result.append(System.lineSeparator() + s);
			}
			br.close();
			// List<String> readLines = IOUtils.readLines(br);
			// String str = StringUtils.join(readLines.toArray(),
			// System.lineSeparator());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}

	/**
	 * TODO 删除一个文件或者一个文件夹下的所有文件(删除后无法恢复!!!)
	 * 
	 * @author zhanghan
	 * @date 2017-2-9
	 * @param path
	 */
	public static void clearAndDelete(String path) {
		File file = new File(path);
		if (file.exists()) {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (File tempFile : files) {
					if (tempFile.isDirectory()) {
						clearAndDelete(tempFile.getAbsolutePath());
					}
					tempFile.delete();
				}
			}
			file.delete();
		}
	}

	/**
	 * TODO 仅删除该目录下的文件,不删除文件夹
	 * 
	 * @author zhanghan
	 * @date 2017-2-9
	 * @param file
	 */
	public static void deleteFileInForlder(String filePath) {
		File file = new File(filePath);
		File[] files = file.listFiles();
		for (File tempFile : files) {
			if (tempFile.isFile()) {
				tempFile.delete();
			}
		}
	}

	/**
	 * TODO
	 * 
	 * @author zhanghan
	 * @date 2017年3月10日
	 * @return
	 * @throws Exception
	 */
	public static String transferToImage(String stream, String basePath, String fileNo) throws Exception {
		// String basePath = request.getRealPath(File.separator);
		String relativePath = "upload/picture/" + System.currentTimeMillis() + "_" + fileNo + ".jpg";
		String imgFilePath = basePath + relativePath;// "D:\\testdata\\222.jpg";//新生成的图片
		File file = new File(basePath + "upload/picture/");
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
		} else {
			clearAndDelete(basePath + "upload/picture/");
		}
		boolean t = stream.matches("^[A-Za-z0-9]+$");
		try {
			if (!t) {
				generateImageByBASE64(stream, imgFilePath);
			} else {
				generateImage(stream, imgFilePath);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return relativePath;
	}

	public static void generateImage(String stream, String imgFilePath) throws Exception {
		OutputStream out = new FileOutputStream(imgFilePath);
		byte[] fileStream = hex2byte(stream);
		InputStream in = new ByteArrayInputStream(fileStream);
		try {
			byte[] b = new byte[1024];
			int nRead = 0;
			while ((nRead = in.read(b)) != -1) {
				out.write(b, 0, nRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			in.close();
			out.close();
		}
	}

	public static void generateImageByBASE64(String stream, String imgFilePath) throws Exception {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(stream);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static byte[] hex2byte(String str) { // 字符串转二进制
		if (str == null)
			return null;
		str = str.trim();
		int len = str.length();
		if (len == 0 || len % 2 == 1)
			return null;
		byte[] b = new byte[len / 2];
		try {
			for (int i = 0; i < str.length(); i += 2) {
				b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue();
			}
			return b;
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * TODO 文件下载
	 * 
	 * @param byts
	 *            二进制流文件
	 * @param fileName
	 *            包含文件后缀名即包含类型
	 */
	public static void writeToResponse(HttpServletResponse response, byte[] buf, String fileName) {

		try {
			// 清空response
			response.reset();
			// 设置response的Header
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Content-Length", "" + buf.length);
			response.setContentType("Application/octet-stream;charset=utf-8");

			OutputStream outputStream = response.getOutputStream();
			IOUtils.write(buf, outputStream);
			IOUtils.closeQuietly(outputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成导出文件名称
	 * 
	 * @Desc:
	 * @date:Nov 17, 2017 9:12:25 AM
	 * @param fileName
	 * @return
	 */
	public static String getExportFileName(String fileName) {
		Date date = new Date();
		// 设置要导出的文件名称
		StringBuilder sub = new StringBuilder();
		sub.append(fileName).append("-");
		sub.append(DateUtils.formatDatetime(date));
		String str = sub.toString();
		return str;
	}

}
